<template>
    <van-sticky>
        <van-nav-bar
            title="我的优惠卷"
            left-text="返回"
            left-arrow
            placeholder
            @click-left="onBack"
            
        />
    </van-sticky>

    <van-address-list
        v-model="active"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
        v-if="action == 'order'"
    />

    <van-address-list
    v-model="active"
    :list="list"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="onDefault"
    v-else
    />

</template>

<script setup>

const { proxy } = getCurrentInstance();
const active = ref(0);// 选中地址
const list = ref([]);// 当前登录用户的收货地址
const business = proxy.$business;
const action = ref(proxy.$route.query.action ?? '');
console.log(action.value);

onBeforeMount(() => {
    getAddressData();
})

const getAddressData = async () =>
{
    let result = await proxy.$http.post({
        url:'/address/index',
        params:{
            busid:business.value.id
        }
    })

    if(result.code === 1)
    {
        for(let item of result.data)
        {
            list.value.push({
                id:item.id,
                name:item.consignee,
                tel:item.mobile,
                address:`${item.region_text} ${item.address}`,
                isDefault:item.status == 1 ? true : false
            });

            if(item.status == 1)
            {
                active.value = item.id;
            }
        }
    }else{
        proxy.$warning(result.msg);
    }
}
const onDefault=async (info,index) =>{
   let params = {
    id:info.id,
    busid:business.value.id
   }

   let result = await proxy.$http.post({
    url:'/address/select',
    params
   })
    if(result.code === 1){

        console.log(list);
        
      let a= list.value.map(item => item.isDefault = false);

        list.value[index].isDefault = true;
        
    }else{
        proxy.$warning(result.msg);
    }
   
}
const onSelect = (info) =>
{
    proxy.$address.value = {
        id:info.id,
        consignee:info.name,
        mobile:info.tel,
        address:info.address
    }

    onBack();
    
}

const onBack = () => proxy.$router.back();
const onAdd = () => proxy.$router.push('/address/add');
const onEdit = (info) => proxy.$router.push({path:'/address/edit',query:{id:info.id}});
</script>